/******************************************************************************
This file is part of AppKit.
Project: appkit
Author : FergusZeng
Email  : cblock@126.com
git	   : https://gitee.com/newgolo/appkit.git
*******************************************************************************
MIT License

Copyright (c) 2022 cblock@126.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "appkit/strutil.h"

#include <ctype.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

#include "appkit/fileio.h"
#include "appkit/tracer.h"

namespace appkit {
std::string StrUtil::toLower(const std::string& str) {
    std::string rc = "";
    const char* pstr = CSTR(str);
    int i = 0;
    char ch = *(pstr + i);
    while (ch != 0) {
        rc.append(1, static_cast<char>(tolower(ch)));
        ch = *(pstr + (++i));
    }
    return rc;
}

std::string StrUtil::toUpper(const std::string& str) {
    std::string rc = "";
    const char* pstr = CSTR(str);
    int i = 0;
    char ch = *(pstr + i);
    while (ch != 0) {
        rc.append(1, static_cast<char>(toupper(ch)));
        ch = *(pstr + (++i));
    }
    return rc;
}

std::string StrUtil::format(const char* fmt, ...) {
    va_list argp;
    va_start(argp, fmt);
    char buf[1024] = {0};
    vsnprintf(buf, sizeof(buf), fmt, argp);
    va_end(argp);
    return std::string(buf);
}

int StrUtil::compare(const std::string& str1, const std::string& str2) {
    size_t p1 = 0;
    size_t p2 = 0;
    while (p1 < str1.size() && p2 < str2.size() && str1[p1] == str2[p2]) {
        p1++;
        p2++;
    }
    if (p1 == str1.size()) {
        p1 = 0;
    } else {
        p1 = (uint8)str1[p1];
    }
    if (p2 == str2.size()) {
        p2 = 0;
    } else {
        p2 = (uint8)str2[p2];
    }
    return p1 - p2;
}

std::string StrUtil::replaceString(const std::string& source,
                                   const std::string& str,
                                   const std::string& rep) {
    std::string result = "";
    std::size_t pos = 0;
    while (1) {
        std::size_t findPos = source.find(str, pos);
        if (findPos != std::string::npos) {
            result.append(source, pos, findPos - pos);
            result.append(rep);
            pos = findPos + str.size();
        } else {
            result.append(source, pos, source.size() - pos);
            break;
        }
    }
    return result;
}

std::string StrUtil::suffix(const std::string& source,
                            const std::string& suffixFlag) {
    auto startPos = source.rfind(suffixFlag);
    if (startPos == std::string::npos) {
        return "";
    }
    std::string sfx = source.substr(startPos);
    if (sfx.find("/") != std::string::npos) {
        return "";
    }
    return sfx;
}

std::string StrUtil::findString(const std::string& source,
                                const std::string& start,
                                const std::string& end) {
    std::string restStr;
    std::size_t startPos, endPos;
    // 找出匹配关键字
    startPos = source.find(start, 0);
    if (startPos == std::string::npos) {
        TRACE_DBG("StrUtil::findString,no start[%s]...", CSTR(start));
        return "";
    }

    endPos = source.find(end, startPos + 1);
    if (endPos == std::string::npos) {
        TRACE_DBG("StrUtil::findString,no end[%s]...", CSTR(end));
        return "";
    }

    return source.substr(startPos, endPos - startPos + end.size());
}

std::string StrUtil::findString(const std::string& source,
                                const std::string& pattern,
                                const std::string& before,
                                const std::string& after) {
    std::string restStr;
    std::size_t startPos, endPos;
    // 找出匹配关键字
    startPos = source.find(pattern, 0);
    if (startPos == std::string::npos) {
        TRACE_DBG("StrUtil::findString,no pattern[%s]...", CSTR(pattern));
        return "";
    }

    /* 从匹配关键字开始查找字符串 */
    restStr = source.substr(startPos);
    startPos = restStr.find(before, 0);
    if (startPos == std::string::npos) {
        TRACE_DBG("StrUtil::findString,no before[%s]...", CSTR(before));
        return "";
    }
    /* 跳过before字串 */
    startPos += before.size();
    endPos = restStr.find(after, startPos);
    if (endPos == std::string::npos) {
        TRACE_DBG("StrUtil::findString,no after[%s]...", CSTR(after));
        return "";
    }
    /* 截取before与after之间的字串 */
    return restStr.substr(startPos, endPos - startPos);
}

std::string StrUtil::trimHeadWith(const std::string& source,
                                  const std::string& trimch) {
    std::string result;
    int len = source.size();
    int trimLen = trimch.size();
    int i = 0;
    while (i < len) {
        int j;
        for (j = 0; j < trimLen; j++) {
            if (source[i] == trimch[j]) {
                break;
            }
        }
        if (j == trimLen) {
            result = source.substr(i);
            break;
        }
        i++;
    }
    return result;
}

std::string StrUtil::trimTailBlank(const std::string& source, bool trimHead,
                                   bool trimTail) {
    std::string result;
    if (trimHead) {
        int len = source.size();
        for (auto i = 0; i < len; i++) {
            if (source[i] > 32) {
                result = source.substr(i);
                break;
            }
        }
    }
    if (trimTail) {
        int len = source.size();
        for (auto i = 0; i < len; i++) {
            if (source[len - 1 - i] > 32) {
                result = source.substr(0, len - i);
                break;
            }
        }
    }
    return result;
}

std::string StrUtil::trimAllBlank(const std::string& source) {
    int i = 0;
    int len = source.size();
    std::string result = "";
    while (i < len) {
        if (source[i] > 32) {
            result.append(1, source[i]);
        }
        i++;
    }
    return result;
}

std::string StrUtil::trimHeadUnvisible(const std::string& source) {
    int i = 0;
    int len = source.size();
    std::string result = "";
    while (i < len) {
        if (source[i] > 32) {
            result.append(1, source[i]);
        } else {
            break;
        }
        i++;
    }
    return result;
}

std::vector<std::string> StrUtil::splitString(const std::string& source,
                                              const std::string& splitFlag,
                                              bool withFlag) {
    std::vector<std::string> vecResult;
    if (source.empty()) {
        return vecResult;
    }
    if (splitFlag.empty()) {
        vecResult.push_back(source);
        return vecResult;
    }

    std::size_t startPos = 0;
    std::size_t findPos = source.find(splitFlag, 0);
    while (findPos != std::string::npos) {
        if (findPos != startPos) {
            vecResult.emplace_back(source.substr(startPos, findPos - startPos));
        }
        if (withFlag) {
            vecResult.emplace_back(source.substr(findPos, splitFlag.size()));
        }
        startPos = findPos + splitFlag.size();
        findPos = source.find(splitFlag, startPos);
    }
    if (startPos < source.size()) {
        vecResult.emplace_back(
            source.substr(startPos, source.size() - startPos));
    }
    return vecResult;
}

std::vector<std::string> StrUtil::cutString(const std::string& source,
                                            const std::string& startFlag,
                                            const std::string& endFlag,
                                            const std::string& cutFlag) {
    std::vector<std::string> vecResult;
    std::size_t startPos = source.find(startFlag);
    std::size_t endPos = source.find(endFlag);
    if (source.empty() || startFlag.empty() || endFlag.empty() ||
        cutFlag.empty() || startPos == std::string::npos ||
        endPos == std::string::npos) {
        return vecResult;
    }
    startPos += startFlag.length();
    if (endPos <= startPos) {
        return vecResult;
    }

    std::size_t searchPos;
    while (((endPos != std::string::npos) && (endPos > startPos)) ||
           (endPos == std::string::npos)) {
        searchPos = source.find(cutFlag, startPos);
        if (searchPos == std::string::npos) {
            if (endPos != std::string::npos)
                vecResult.emplace_back(
                    source.substr(startPos, endPos - startPos));
            else
                vecResult.emplace_back(source.substr(startPos));
            break;
        }
        vecResult.emplace_back(source.substr(startPos, searchPos - startPos));
        startPos = searchPos + cutFlag.length();
    }
    return vecResult;
}

int StrUtil::patternCount(const std::string& source,
                          const std::string& pattern) {
    std::size_t atFind = 0;
    int i = 0;
    if (source.empty() || pattern.empty()) {
        return 0;
    }
    for (;;) {
        atFind = source.find(pattern, atFind);
        if (atFind != std::string::npos) {
            atFind += pattern.size();
            i++;
        } else {
            break;
        }
    }
    return i;
}

int StrUtil::ctoi(char ch) {
    if (ch >= 'a' && ch <= 'f') {
        return (ch - 'a' + 0x0A);
    } else if (ch >= 'A' && ch <= 'F') {
        return (ch - 'A' + 0x0A);
    } else if (ch >= '0' && ch <= '9') {
        return (ch - '0');
    } else {
        return -1;
    }
}

char StrUtil::itoc(int val) {
    if (val >= 0 && val <= 9) {
        return (val + '0');
    } else if (val >= 0x0A && val <= 0x0F) {
        return (val - 0x0A + 'A');
    } else {
        return 0;
    }
}

int StrUtil::htoi(const std::string& hexStr) {
    int result = 0;
    const char* pHex = CSTR(hexStr);
    while ((*pHex) != '\0') {
        result = (result << 4) + StrUtil::ctoi(*pHex);
        pHex++;
    }
    return result;
}

int StrUtil::hexBinarize(const std::string& hexStr, char* buffer, int len) {
    int i;
    if (hexStr.empty() || !buffer) {
        TRACE_ERR("StrUtil::hexBinarize parameter error.");
        return RC_ERROR;
    }
    if (len < hexStr.size() / 2) {
        TRACE_ERR("StrUtil::hexBinarize buf len(%d) error.", len);
        return RC_ERROR;
    }

    for (i = 0; i < hexStr.size() / 2; i++) {
        sint8 a, b;
        a = StrUtil::ctoi(hexStr[2 * i]);
        b = StrUtil::ctoi(hexStr[2 * i + 1]);
        if (-1 == a || -1 == b) {
            TRACE_ERR("StrUtil::hexBinarize invalid string.");
            return RC_ERROR;
        }
        buffer[i] = (a << 4) + b;
    }
    return i;
}

std::string StrUtil::hexVisualize(const std::string& codestr) {
    return hexVisualize(codestr.data(), codestr.size());
}

std::string StrUtil::hexVisualize(const char* buffer, int len) {
    if (!buffer || len <= 0) {
        TRACE_ERR("StrUtil::hexVisualize parameter error.");
        return "";
    }

    std::string hexStr = "";
    for (auto i = 0; i < len; i++) {
        char hex[3] = {0};
        hex[0] = StrUtil::itoc((buffer[i] >> 4) & 0x0F);
        hex[1] = StrUtil::itoc(buffer[i] & 0x0F);
        if (0 == hex[0] || 0 == hex[1]) {
            TRACE_ERR("StrUtil::hexVisualize error.");
            return "";
        }
        hexStr += hex;
        hexStr += " ";
    }
    return hexStr;
}

bool StrUtil::isHexString(const std::string& hexStr) {
    const char* pstr = CSTR(hexStr);
    int len = strlen(pstr);
    int i = 0;
    while (i < len) {
        if ((*(pstr + i) >= '0' && *(pstr + i) <= '9') ||
            (*(pstr + i) >= 'A' && *(pstr + i) <= 'F') ||
            (*(pstr + i) >= 'a' && *(pstr + i) <= 'f')) {
            i++;
            continue;
        } else {
            return false;
        }
    }
    return true;
}

bool StrUtil::isIntString(const std::string& intStr) {
    const char* pstr = CSTR(intStr);
    auto len = strlen(pstr);
    size_t i = 0;
    while (i < len) {
        if (*(pstr + i) >= '0' && *(pstr + i) <= '9') {
            i++;
            continue;
        } else {
            return false;
        }
    }
    return true;
}

/* 在[mem,mem+n)区间查找str,找到返回位置 */
char* StrUtil::memString(char* mem, int n, char* str, int size) {
    char* find = reinterpret_cast<char*>(memchr(mem, str[0], n));
    if (find) {
        char* end = find + size;
        if (end <= mem + n) {
            if (memcmp(find, str, size) == 0) {
                return find;
            } else {
                return memString(find + 1, mem + n - find - 1, str, size);
            }
        }
    }
    return nullptr;
}
}  // namespace appkit
